import tracker from "../utils/tracker";

export function injectXHR(){
  console.log('injectXHR 正在监控 ajax请求 --- ---');

  const XMLHttpRequest = window.XMLHttpRequest;

  const oldOpen = XMLHttpRequest.prototype.open;
  XMLHttpRequest.prototype.open = function (method, url, async) {
    if(!url.match(/logstores/) && !url.match(/sockjs-node/)){
      this.logData = {method, url, async}
    }

    return oldOpen.apply(this, arguments);
  };

  const oldSend = XMLHttpRequest.prototype.send;
  XMLHttpRequest.prototype.send = function(body){
    if (this.logData) {
      const startTime = Date.now();

      const handler = (type) => (event) => {
        const duration = Date.now() - startTime;
        const status = this.status; // 200 | 500 | ...
        const statusText = this.statusText; // ok | Server Error | ...

        tracker.send({
          kind: 'stability',
          type: 'xhr',
          eventType: type, //load error abort //服务端返回500 也是load, 只有请求发送不成功时(断网、网络问题)才会是error
          pathname: this.logData.url, //请求路径
          status: status + '-' + statusText, //状态码
          duration, //持续时间
          response: this.response ? JSON.stringify(this.response) : '', //响应体
          params: body || ''
        });
      };

      this.addEventListener('load',handler('load'),false)
      this.addEventListener('error',handler('error'),false)
      this.addEventListener('abort',handler('abort'),false)
    }
    return oldSend.apply(this, arguments);
  }
}
